﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using AspDemo.Models;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Routing;

namespace AspDemo.Controllers
{
    [Route("api/record")]
    public class RecordController : Controller
    {
        private readonly ApplicationDataContext _dbContext;

        public RecordController(ApplicationDataContext dataContext) : base()
        {
            _dbContext = dataContext;
        }

        /// <summary>
        /// 上传用户测量记录
        /// </summary>
        /// <param name="recordRequst"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<ApiResponse> Upload([FromForm]RecordRequstModel recordRequst)
        {
            var userQuerry = from u in _dbContext.Users
                             where u.UId == recordRequst.Uid
                             select u.UId;

            if (!userQuerry.Any())
            {
                return new(ApiCode.Error, "非法用户", ApiResponse.NullData);
            }

            _dbContext.Records.Add(new Record
            {
                UserId = recordRequst.Uid,
                Time = DateTime.Now,
                HeartRate = recordRequst.HeartRate,
                Temprature = recordRequst.Temprature,
                BloodPressureHigh = recordRequst.HeartRate,
                BloodPressureLow = recordRequst.BloodPressureLow,
                BloodOxygenSaturation = recordRequst.BloodOxygenSaturation
            });

            await _dbContext.SaveChangesAsync();

            return new(ApiCode.Success, "上传成功", ApiResponse.NullData);
        }

        public class RecordRequstModel
        {
            /// <summary>
            /// 用户ID
            /// </summary>
            [Required]
            [MaxLength(200)]
            public string Uid { get; set; }
            /// <summary>
            /// 心率
            /// </summary>
            [Required]
            public int HeartRate { get; set; }
            [Required]
            public float Temprature { get; set; }
            [Required]
            public int BloodPressureHigh { get; set; }
            [Required]
            public int BloodPressureLow { get; set; }
            [Required]
            public float BloodOxygenSaturation { get; set; }
        }
    }
}
